import { setItem, getItem, removeAllItem } from '../../utils/storage'
import { TOKEN } from '../../constant'
import { getUserInfo } from '../../api/user'
import router, { resetRouter } from '../../router'
import { Module } from 'vuex'
import { Store } from '../../../typings/store'

const user:Module<Store.userState,any> = {
    namespaced: true,
    state: () => ({
      token: getItem(TOKEN) || '',
      userInfo: {}
    }),
    mutations: {
      setToken (state, token:string) {
        state.token = token
        setItem(TOKEN, token)
      },
      setUserInfo (state, userInfo:{}) {
        state.userInfo = userInfo
      }
    },
    actions: {
      asyncSetToken({commit},token:string) {
        commit('setToken',token)
      },
      async getUserInfo({ commit }) {
        const res = await getUserInfo()
        if(res.code==200) {
          commit('setUserInfo', res.data)
          return res.data
        }
      },
      // 退出登录
      logout ({commit}) {
        resetRouter()
        commit('user/setUserInfo', {})
        commit('user/setToken', '')
        removeAllItem()
        router.push('/login')
      }
    }
}
export default user;